﻿using System.Text;
using Sanelib.Common.SystemSettings;

namespace Sanelib.CodeMaker.Generators
{
    public class EntityGenerator
    {
        public static void Generate(DatabaseTableSchema tbSchema)
        {
            var sb = new StringBuilder();
            DefaultHeader(tbSchema, sb);
            CreateProperties(tbSchema, sb);
            StoredProcedureMapping(tbSchema, sb);
            DefaultFooter(sb);

            System.IO.File.WriteAllText(Globals.CreateOrGetCustomPath("..\\Core\\Domain\\Model\\") + tbSchema.TableName + "_Generated.cs", sb.ToString());
        }

        private static void DefaultHeader(DatabaseTableSchema tbSchema, StringBuilder sb)
        {
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Data;");
            sb.AppendLine("using Sanelib.DataOperation;");
            sb.AppendLine("using Sanelib.DataOperation.Attribute;");
            sb.AppendLine("using Sanelib.DataOperation.Base;");
            sb.AppendLine("");
            sb.AppendLine("namespace Core.Domain.Model");
            sb.AppendLine("{");
            sb.AppendLine("\t[EntityName(\"" + tbSchema.TableName + "\")]");
            sb.AppendLine("\tpublic class " + tbSchema.TableName + " : " + (tbSchema.IsAudited ? "AuditedEntity" : "Entity"));
            sb.AppendLine("\t{");
        }

        private static void CreateProperties(DatabaseTableSchema tbSchema, StringBuilder sb)
        {
            foreach (var item in tbSchema.Columns)
            {
                sb.AppendLine(item.GetPropertyDeclaration("\t\t"));
            }
        }

        private static void StoredProcedureMapping(DatabaseTableSchema tbSchema, StringBuilder sb)
        {
            sb.AppendLine("");
            sb.AppendLine("\t\tpublic override void From(IDataReader dataReader)");
            sb.AppendLine("\t\t{");
            sb.AppendLine("\t\t\tbase.From(dataReader);");
            foreach (var item in tbSchema.Columns)
            {
                sb.AppendLine("\t\t\t" + item.GetFromMapping());
            }
            sb.AppendLine("\t\t}");
            sb.AppendLine("");
            sb.AppendLine("\t\tpublic override void To(System.Data.SqlClient.SqlCommand cmd)");
            sb.AppendLine("\t\t{");
            sb.AppendLine("\t\t\tbase.To(cmd);");
            foreach (var item in tbSchema.Columns)
            {
                sb.AppendLine("\t\t\t" + item.GetToMapping());
            }
            sb.AppendLine("\t\t}");
        }

        public static void DefaultFooter(StringBuilder sb)
        {
            sb.AppendLine("\t}");
            sb.AppendLine("}");
        }
    }
}
